/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



package org.crane.webtemplate;


import java.lang.reflect.Field;
import java.net.URL;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.crane.webtemplate.dao.HibernateUtil;
import org.crane.webtemplate.model.choice.BasicChoice;

/**
 * Web application lifecycle listener.
 * @author CraneLeeon
 */
public class AppListener implements ServletContextListener {
    protected final static Log logger = LogFactory.getLog(AppListener.class);

    public void contextInitialized(ServletContextEvent evt) {
        ServletContext ctx = evt.getServletContext();
        //CONFIG PARAMS
        for (Enumeration<String> e = ctx.getInitParameterNames() ; e.hasMoreElements() ;) {
            String key = e.nextElement();
            String val = ctx.getInitParameter(key);
            if(key.endsWith(".DEFAULT")){//set up .DEFAULT for all BasicChoice subclasses
                try {
                    Class choicetype = Class.forName(key.replaceFirst(".DEFAULT", ""));
                    if(BasicChoice.class.isAssignableFrom(choicetype)){
                        Enum obj = Enum.valueOf(choicetype, val);
                        choicetype.getField("DEFAULT").set(null, obj);
                    }
                } catch (Exception ex) {
                    logger.debug("Initial Parameter Error! ",ex);
                }
            }else if(key.contains(".")){//set static properties in refered classes
                try {
                    if(val.endsWith(".class")){
                        String clsname = key.substring(0, key.lastIndexOf("."));
                        String fname = key.substring(key.lastIndexOf(".")+1);
                        Class cls = Class.forName(clsname);
                        Field field = cls.getField(fname);
//                        Object obj = cls.newInstance();
                        field.set(null, Class.forName(val.replaceFirst(".class", "")));
                    }else{
                        String clsname = key.substring(0, key.lastIndexOf("."));
                        String fname = key.substring(key.lastIndexOf(".")+1);
                        Class cls = Class.forName(clsname);
                        Field field = cls.getField(fname);
//                        Object obj = cls.newInstance();
                        field.set(null, field.getType()
                                .getMethod("valueOf",
                                    ((field.getType().equals(String.class))? Object.class:String.class)
                                ).invoke(null,val));
                    }
                } catch (Exception ex) {
                    logger.debug("Initial Parameter Error! ",ex);
                }

            }
        }
        
        //initial log4j
        URL logurl = null;
        try {
//            logurl = ctx.getResource("/WEB-INF/log4j.properties");
            logurl = ClassLoader.getSystemResource("log4j.properties");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (logurl != null) {
            PropertyConfigurator.configure(logurl);
        }
        //initial hibernate
        try {
//            HibernateUtil.initial(ctx.getResource("/WEB-INF/hibernate.cfg.xml"), false);
            HibernateUtil.initial(false);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public void contextDestroyed(ServletContextEvent evt) {

    }
}
